package com.handler;

import com.yly.User;
import com.yly.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by tj on 2016/10/10.
 */
@RestController
public class MController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private BetService betService;

    @RequestMapping(path = "/jRedirect", method = RequestMethod.GET)
    public String getName() {
        return "redirect:/modelandview";
    }

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    public String getUserName(@RequestParam(value = "id", defaultValue = "2") int id) {
        return userDao.getUser(id);
    }

    @RequestMapping(value = "/modelandview", method = RequestMethod.GET)
    public ModelAndView printHello() {
        ModelAndView view = new ModelAndView("/test");
        view.addObject("message", "ke yi le");
        return view;
    }

    @RequestMapping(value = "/jsonUser", method = RequestMethod.GET)
    public User jsonUser() {
        return new User(1038, "yulinye", "123456");
    }

    @RequestMapping(value = "/commitJson", method = RequestMethod.POST)
    public String commitJson(@RequestBody User json) {
        return json.getUsername();
//        userDao.addUser(json);
//        return "insert ok";
    }

    @RequestMapping("/something")
    public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
        String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader");
        byte[] requestBody = requestEntity.getBody();

        // do something with request header and body

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("MyResponseHeader", "MyValue");
        ResponseEntity<String> result =  new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
        return result;
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String commitJson(@RequestParam String name) {
        return name;
//        userDao.addUser(json);
//        return "insert ok";
    }

//    @RequestMapping(value = "/commitBet", method = RequestMethod.GET)
//    public String commitBet() {
//        betService.parse();
//        return "ok";
//    }

    @RequestMapping(value = "/jiaye", method = RequestMethod.GET)
    public void calJiaye() {
        betService.calcHistory();
    }


}
